<template>
  <div class="w-full h-full " style="background: #f8f8f8">
    <div class="w-full h-full shadow-lg rounded-xl bg-white pt-3 px-5">
      <div class="flex items-center mb-2">
        <div class="flex items-center bg-indigo-50/60 rounded-lg py-0.5 px-2">
          <i class="iconfont icon-shishikucunshiyitu text-indigo-500 text-base"/>
          <span class="title font-semibold text-indigo-600 ml-1.5">{{ $t('tank.OverviewOutbound') }}</span>
        </div>
        <div class="flex-1 h-[1px] bg-gradient-to-r from-indigo-200 via-indigo-100/50 to-transparent ml-3"></div>
        <el-form :inline="true" :model="from" class="align-center search-form mb-4">
          <el-form-item class="label" :label="$t('iot.time')">
            <el-date-picker
              style="width: 220px"
              v-model="from.time2"
              type="daterange"
              range-separator="-"
              format="YYYY-MM-DD" value-format="YYYY-MM-DD"
              :disabled-date="disabledDate"
              :start-placeholder="$t('wms.startTime')"
              :end-placeholder="$t('wms.endTime')"
              class="custom-date-picker"
            />
          </el-form-item>
          <el-button icon="Search" class="buttons" type="primary" @click="getEndSerch">{{$t('wms.search')}}</el-button>
        </el-form>
      </div>
      <div class="table-list w-full h-full">
        <el-table
          ref="tableRef"
          border
          id="out-table"
          :data="endList"
          :fit="true"
          table-layout="fixed"
          header-align="center"
          v-loading="endLoading"
          style="width:100%;height: 85%;"
          :header-cell-style="{
        color: '#1e293b',
        textAlign: 'center',
        fontWeight: '600',
        background: 'linear-gradient(to bottom, #f8fafc, #f1f5f9)',
        borderColor: '#e2e8f0',
        height: '40px'
      }"
          :cell-style="{
        textAlign: 'center',
        color: '#334155',
        borderColor: '#e2e8f0',
        background: '#fff',
        height: '40px'
      }"
        >
          <el-table-column prop="type" :label="$t('mes.operateType')" width="150" show-overflow-tooltip>
            <template #default="scope">
              <el-tag type="info" style="width: 80px" effect="light">{{  scope.row.type }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="tankCode" :label="$t('tank.TankNumber')" width="150" show-overflow-tooltip>
            <template #default="scope">
              <el-tag :type="scope.row.isUse? 'primary' : 'info'" effect="light">{{  scope.row.tankCode }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column :label="$t('tank.chuku')">
            <el-table-column prop="outNowQty" :label="$t('tank.benrixiaoh')" width="150" show-overflow-tooltip>
              <template #default="scope">
                <el-tag
                  type="primary"
                  effect="light"
                >
                  {{  scope.row.outNowQty }} kg
                </el-tag>
              </template>
            </el-table-column>

          <el-table-column prop="outQty" :label="$t('tank.outboundQuantity')">
            <template #default="scope">
              <el-tag
                :type="scope.row.outQty > 0 ? 'success' : 'warning'"
                effect="light"
              >
                <el-link type="success" @click="jumpOut(scope.row)">{{ scope.row.outQty }} kg</el-link>
              </el-tag>
            </template>
          </el-table-column>
            <el-table-column prop="batchNum" :label="$t('tank.benrHunl')" width="150" show-overflow-tooltip/>
          </el-table-column>


          <el-table-column :label="$t('tank.ruku')">
            <el-table-column prop="inQty" :label="$t('tank.itemsReceived')">
              <template #default="scope">
                <el-tag
                  :type="scope.row.inQty > 0 ? 'success' : 'warning'"
                  effect="light"
                >
                  <el-link type="success" @click="jumpIn(scope.row)">{{ scope.row.inQty }} kg</el-link>
                </el-tag>
              </template>
            </el-table-column>

            <el-table-column prop="lastPutTime" :label="$t('tank.LatestDate')" show-overflow-tooltip/>
            <el-table-column prop="lastPutQty" :label="$t('tank.LastInboundt')">
              <template #default="scope">
               <span :class="{ 'highlight-green': scope.row.lastPutQty > 0 }">
                {{ scope.row.lastPutQty}} kg
              </span>
              </template>
            </el-table-column>
          </el-table-column>
          <el-table-column prop="beginQty" :label="$t('tank.LastMonthQuantity')">
            <template #default="scope">
              <el-tag
                :type="scope.row.beginQty > 0 ? 'primary' : 'warning'"
                effect="light"
              >
              <span :class="{ 'highlight': scope.row.beginQty > 0 }">
                {{ scope.row.beginQty }} kg
              </span>
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="tankQty" :label="$t('tank.TankWeight')">
            <template #default="scope">
              <el-tag
                :type="scope.row.tankQty > 0 ? 'success' : 'info'"
                effect="light"
              >
                {{ scope.row.tankQty > 0 ? scope.row.tankQty : 0}} kg
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="materialCode" :label="$t('tank.MaterialNumber')" width="150" show-overflow-tooltip/>
          <el-table-column prop="materialName" :label="$t('tank.MaterialName')" width="150" show-overflow-tooltip/>
          <el-table-column prop="spec" :label="$t('tank.Specification')" show-overflow-tooltip/>




        </el-table>

<!--        <div class="flex justify-end mt-3">-->
<!--          <el-pagination-->
<!--            :current-page="data.endpage"-->
<!--            :page-size="data.endSize"-->
<!--            :page-sizes="[10, 20, 50, 100]"-->
<!--            small-->
<!--            background-->
<!--            class="custom-pagination"-->
<!--            layout="total, sizes, prev, pager, next, jumper"-->
<!--            :total="data.endListTotal"-->
<!--            @size-change="handleEndSizeChange"-->
<!--            @current-change="handleEndCurrentChange"-->
<!--          />-->
<!--        </div>-->
      </div>

    </div>
  </div>
</template>
<script setup>
import moment from 'moment';
import { onMounted, reactive, ref ,watch} from 'vue'
import { ElMessage } from 'element-plus';
import { getTankOutNum } from '@/api/tankBodyApi'
import { useRoute, useRouter } from 'vue-router'
import useI18n from '@/hooks/language'

const { t } = useI18n()
const route = useRoute()
const router = useRouter()

const endList = ref([])
const endLoading = ref(false)
const  data  = reactive({
  endListTotal:0,
  endSize:10,
  endpage:1,
})
const from = reactive({
  time: [],
  time2: [],
})
const disabledDate = (time) => {
  // 如果未选择任何时间，允许选择所有日期
  if (!from.time2 || from.time2.length === 0) return false;
  const [startStr, endStr] = from.time2;
  const start = startStr ? new Date(startStr) : null;
  const end = endStr ? new Date(endStr) : null;

  // 检查 start 和 end 是否为有效的日期对象
  if (start && isNaN(start.getTime())) {
    console.error('Invalid start date:', startStr);
    return false;
  }
  if (end && isNaN(end.getTime())) {
    console.error('Invalid end date:', endStr);
    return false;
  }

  // 只选择了开始时间，限制结束时间只能在同月
  if (start && !end) {
    const startYear = start.getFullYear();
    const startMonth = start.getMonth();
    return time.getFullYear() !== startYear || time.getMonth() !== startMonth;
  }
  // 只选择了结束时间，限制开始时间只能在同月
  if (!start && end) {
    const endYear = end.getFullYear();
    const endMonth = end.getMonth();
    return time.getFullYear() !== endYear || time.getMonth() !== endMonth;
  }
  // 已经选择了开始和结束时间，限制只能在同月
  if (start && end) {
    const startYear = start.getFullYear();
    const startMonth = start.getMonth();
    const endYear = end.getFullYear();
    const endMonth = end.getMonth();
    return startYear !== endYear || startMonth !== endMonth || time.getFullYear() !== startYear || time.getMonth() !== startMonth;
  }
  return false;
};
watch(
  () => from.time2,
  (val) => {
    if (val && val.length === 2) {
      const [startStr, endStr] = val;
      const start = new Date(startStr);
      const end = new Date(endStr);
      if (start && end) {
        const startYear = start.getFullYear();
        const startMonth = start.getMonth();
        const endYear = end.getFullYear();
        const endMonth = end.getMonth();
        if (startYear !== endYear || startMonth !== endMonth) {
          from.time2 = [];
          ElMessage.error(t('tank.sameMonth'));
        }
      }
    }
  },
  { deep: true }
);

const formatNumber= (num) => {
  if (Number.isInteger(Number(num))) {
    return num;
  }
  return parseFloat(num).toFixed(2) || "--"
}
const getEndList = async () => {
  endLoading.value = true
  try {
    const params = {
      startTime: from?.time2?.[0] ? moment(from.time2[0]).format('YYYY-MM-DD') : '',
      endTime:  from?.time2?.[1] ? moment(from.time2[1]).format('YYYY-MM-DD') : '',
      // current:data.endpage,
      // size:data.endSize,
    }
    const res = await getTankOutNum(params)
    endList.value = res.data.map((item)=>{
      return {
        ...item,
        beginQty: formatNumber(item.beginQty),
        inQty: formatNumber(item.inQty),
        outQty: formatNumber(item.outQty),
        tankQty: formatNumber(item.tankQty),
        lastPutQty: formatNumber(item.lastPutQty),
      }
    })
    // data.endListTotal = res.data.total
  } catch (e) {
    console.log(e)
  } finally {
    endLoading.value = false
  }
}

const getEndSerch=()=>{
  getEndList()
}

const getDefaultDateRange = () => {
  const today = moment();
  const startOfMonth = today.clone().startOf('month').format('YYYY-MM-DD');
  const endOfMonth = today.clone().format('YYYY-MM-DD');  // 结束日期为今天

  from.time2 = [startOfMonth, endOfMonth];
}


const jumpIn = (item) => {
  //路由跳转并携带时间参数
  router.push({
    path: '/InventoryDetails',
    query: {
      startTime: from?.time2?.[0] ? moment(from.time2[0]).format('YYYY-MM-DD') : '',
      endTime:  from?.time2?.[1] ? moment(from.time2[1]).format('YYYY-MM-DD') : '',
      tankCode:  item.tankCode,
      materialCode:  item.materialCode,
    },
  });

}
const jumpOut = (item) => {
  router.push({
    path: '/PreMixedDetails',
    query: {
      startTime: from?.time2?.[0] ? moment(from.time2[0]).format('YYYY-MM-DD') : '',
      endTime:  from?.time2?.[1] ? moment(from.time2[1]).format('YYYY-MM-DD') : '',
      tankCode:  item.tankCode,
      materialCode:  item.materialCode,
    },
  });
}

onMounted(async () => {
 await getDefaultDateRange()
  getEndList()
})

const handleEndSizeChange = (val) => {
  data.endSize = val
  getEndList()
}
const handleEndCurrentChange = (val) => {
  data.endpage = val
  getEndList()
}
</script>


<style scoped lang="scss">
:deep(.el-form) {
  height: 18px;
  display: flex;
  justify-content: center;
}
.highlight {
  color: #409EFF;
  font-weight: bold;
}

.highlight-green {
  color: #67C23A;
  font-weight: bold;
}

.highlight-red {
  color: #F56C6C;
  font-weight: bold;
}
</style>
